package com.maimao.goods.job;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.maimao.core.constant.RedisKeys;
import com.maimao.core.utils.DateUtils;
import com.maimao.goods.mapper.GoodsMapper;
import com.maimao.model.goods.dto.GoodsClickDto;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 同步Redis中商品的每日点击数据到数据库 每日零点执行
 *
 * @author MaoLin Wang
 * @date 2021/3/31 10:59 下午
 */
@Component
public class SyncEveryDayClickDataJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsMapper goodsMapper;


    @XxlJob("SyncEveryDayClickDataJob")
    public ReturnT SyncEveryDayClickData() {
        Map<String, Integer> entries = redisTemplate.opsForHash().entries(getRedisKey());
        XxlJobHelper.log("获取到待同步点击数据：{}，大小:{}", entries, entries.size());
        if (ObjectUtil.isNotEmpty(entries)) {
            List<GoodsClickDto> list = Lists.newArrayListWithCapacity(entries.size());
            GoodsClickDto dto;
            for (Map.Entry<String, Integer> entry : entries.entrySet()) {
                String goodsId = entry.getKey();
                if (StrUtil.isEmpty(goodsId)) {
                    continue;
                }
                Long count = Long.valueOf(entry.getValue());

                dto = new GoodsClickDto(Convert.toLong(goodsId), count == null ? 0 : count);
                list.add(dto);
            }
            XxlJobHelper.log("准备同步点击数据到数据库：{}，大小:{}", list, list.size());
            try {
                goodsMapper.updateClickCountBatch(list);
            } catch (Exception e) {
                XxlJobHelper.log("同步数据到数据库失败,原因:{}", e.getMessage());
                return ReturnT.FAIL;
            }
        }
        XxlJobHelper.log("同步成功");

        return ReturnT.SUCCESS;
    }

    public String getRedisKey() {
        String format = DateUtils.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return String.format(RedisKeys.GOODS_CLICK_COUNT, format);
    }
}
